/**
 * http请求服务类
 */

import unistore from '../store/index'
import unicore from './core.service'
import { getHeader,getImgHeader } from './config.service'


// 开发环境
let baseUrl = unicore.config.baseUrl;
// #ifdef MP
// baseUrl = "https://uat.baoyjr.com"
// #endif

import requestFactory from './clz/dealRequstFactory'

let loading = 0;
export default {
	post:(requestUrl:string,data:any,header?:any,noshowToast?:any) => {
		loading++;
		uni.showToast({
			title:"请求中...",
			icon:"loading",
			mask:true,
			duration:60000
		})
		const deal = requestFactory(requestUrl);
		const request = deal.encrapt(data);
		header = deal.getHeader(header);
		header.X_UserToken = unistore.state.common.token
		console.log(data,'<-接口请求信息')
		return new Promise((resolve,reject) =>{
			let timer= setTimeout(()=> {
				loading--;
				if(!loading){
					uni.hideToast();
				}
				console.log('请求超时',loading)
				uni.showToast({
					title:'请求超时',
					icon:'none',
					duration:5000
				})
				reject('请求超时')
			},60000)
			uni.request({
				url:baseUrl + requestUrl,
				data: request,
				method:'POST',
				header,
				success: (res) => {
					if (res.statusCode === 200){
						try {
							// console.log('解密前data->', res.data)
							const data = deal.decrapt(res.data,noshowToast);
							// console.log('解密完data->', data)
							if(data || data === null){
								/**mbars部分接口返回成功，data=null */
								try {
									res.data = JSON.parse(data);
								} catch(e){
									res.data = data;
								}
							} else if(data === undefined){
								//返回报错，即data=undefined
								/**关于报错的提示处理逻辑
								 * reject之后res会被catch捕获
								 * 在catch之后添加弹窗提示
								 */
								reject(res);
							}
						} catch(e) {
							console.log('catch')
							reject(res);
						}
						resolve(res.data);
					}else {
						reject(res);
					}
					
				},
				fail: (err) => {
					reject(err);
				},
				complete: () => {
					clearTimeout(timer)
					loading--;
					if(!loading){
						uni.hideToast();
					}
				}
			});
		}).catch((e)=>{
			if(e.data.jcxysj){
				uni.showToast({
					title:e.data.jcxysj.fhmsxx,
					icon:'none',
					duration:2000,
					mask: true
				})
			}
			
		})
	},
	get:(requestUrl:string,data:object,header?:any) => {
		loading++;
		uni.showToast({
			title:"请求中...",
			icon:"loading",
			mask:true,
			// image: '/static/img/loading.gif',
			duration:60000
		})
		const deal = requestFactory(requestUrl);
		const request = deal.encrapt(data);
		header = deal.getHeader(header);
		
		return new Promise((resolve,reject) =>{
			let timer= setTimeout(()=> {
				loading--;
				if(!loading){
					uni.hideToast();
				}
				console.log('请求超时',loading)
				uni.showToast({
					title:'请求超时',
					icon:'none',
					duration:5000
				})
				reject('请求超时')
			},60000)
			uni.request({
				url:baseUrl + requestUrl,
				data: request,
				method:'GET',
				header,
				success: (res) => {
					if (res.statusCode === 200){//连接成功
						try {
							
							const data = deal.decrapt(res.data);
							if(data){
								res.data = data;
							} else {
								reject(res);
							}
						} catch(e) {
							reject(res);
						}
						resolve(res.data);
					}else {
						reject(res);
					}
					
				},
				fail: (err) => {
					reject(err);
				},
				complete: () => {
					clearTimeout(timer)
					loading--;
					if(!loading){
						uni.hideToast();
					}
				}
			});
		}) 
	},
	imgUpload(requestUrl:string,formData?:any,header?:any,name?:any){
		console.log('开始选择图片')
		formData = formData || {}
		// console.log(header)
		header = getImgHeader(header)
		// console.log(header)
		name = name || 'file'
		return new Promise((resolve,reject) => {
			uni.chooseImage({
				count:1,
				sourceType:['album','camera'],
				success: (chooseImageRes) => {
					console.log('选择图片成功')
					var path = '';
					var tempFiles:any = chooseImageRes.tempFiles;
					var size = tempFiles[0].size;
					if(chooseImageRes.tempFilePaths){
						path = chooseImageRes.tempFilePaths[0];
					}
					loading++;
					uni.showToast({
						title:"上传中...",
						icon:"loading",
						mask:true,
						duration:20000
					})
					console.log(size,"图片压缩前size")
					unicore.interaction.compressImage({
						path,
						success:(resp:any)=>{
							console.log('图片压缩成功')	
							path = resp.tempFilePath
							// formData.append('yxwj',resp.tempFilePath)
							console.log(resp.tempFilePath,'--------------formData')
							console.log('开始上传')	
							// const tempUrl = baseUrl + requestUrl;
							formData[name] = path;
							fetch(resp.tempFilePath).then(bres => bres.blob()).then(blob => {
								const fd = new FormData();
								for(const k in formData) {
									fd.append(k,formData[k]);
								}
								// const tempUrl = isFullUrl?`${requestUrl}?jsonKey=${requestStr}`:`${baseUrl}${requestUrl}?jsonKey=${requestStr}`
								const tempUrl = baseUrl + requestUrl;
								var patharr = resp.tempFilePath.split('/');
								const filename = `file-${patharr[patharr.length-1]}.jpg`
								fd.append(name||'file',blob,filename);
								var xhr = new XMLHttpRequest();
								xhr.open('POST',tempUrl);
								for(const t in header){
									xhr.setRequestHeader(t,header[t])
								}
								xhr.send(fd);
								xhr.onload = (res:any) => {
									try{
										console.log('上传成功')	
										const ret = JSON.parse(res.target.response);
										ret.path = path;
										resolve(ret);
									}catch(err){
										err.path = path
										reject(err)
									}finally{
										loading--;
										if(!loading){
											uni.hideToast();
										}
									}
								}
							})
						}
					})
				}
			});
		})
	}
}


